package com.woniuxy.handler;

import com.alibaba.fastjson.JSON;
import com.woniuxy.config.RedisConfig;
import com.woniuxy.entity.UserInfo;
import com.woniuxy.util.JWTUtil;
import com.woniuxy.util.ResponseData;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author HP
 * 登录成功后的处理器，用于返回json数据
 * 生成jwt
 * 存到redis
 * 带到前端去
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler
{

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication)
            throws IOException, ServletException {
        //生成jwt
        UserInfo userInfo = (UserInfo) authentication.getPrincipal();//获取loadUserByUsername返回的对象

        Map map = new HashMap();
        map.put("userId",userInfo.getUserId());
        map.put("account",userInfo.getUsername());
        //如果我想把用户的id也存到jwt中，可以在这里查询数据库，获取用户的id
        String jwt = JWTUtil.createJWT(map);
        redisTemplate.opsForValue().set("jwt:"+userInfo.getUserId(),jwt,30, TimeUnit.DAYS);


        //返回json数据
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().print(JSON.toJSONString(new ResponseData<>().ok(jwt )));
    }
}
